package top.whysu.edevice.global;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import top.whysu.edevice.constant.CodeConstant;
import top.whysu.edevice.dto.generate.HeaderDTO;
import top.whysu.edevice.dto.generate.ResponseDTO;
import top.whysu.edevice.exception.BusinessException;
import top.whysu.edevice.utils.ResponseUtil;

import javax.servlet.http.HttpServletResponse;

/**
 * 视图层全局异常捕获
 */
@RestController
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理业务异常
     *
     * @param response          响应信息
     * @param businessException 业务异常
     * @return 自定义响应
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResponseDTO processBusinessException(HttpServletResponse response, BusinessException businessException) {

        StackTraceElement stackTraceElement = businessException.getStackTrace()[0];
        // 日志打印
        LOGGER.error("处理业务异常：" + businessException.getMessage(), businessException);
//        LOGGER.error("处理业务异常：响应信息: " + businessException.getMessage()
//                + ", 响应码:" + businessException.getCode()
//                + ", 类：" + stackTraceElement.getClassName()
//                + ", 行：" + stackTraceElement.getLineNumber());
        // 封装HTTP响应
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        // 封装自定义响应
        return ResponseUtil.getFailResponse(new HeaderDTO(), businessException.getCode(), businessException.getMessage());
    }

    /**
     * Validated校验参数错误异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    protected ResponseDTO validationBodyException(HttpServletResponse response, MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        // 封装HTTP响应
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        String message;
        if (StringUtils.isNotEmpty(fieldError.getDefaultMessage())) {
            message = fieldError.getDefaultMessage();
        } else {
            message = String.format("%s参数错误", fieldError.getField());
        }
        return ResponseUtil.getFailResponse(new HeaderDTO(), CodeConstant.Http.EXECUTE_FAIL, message);
    }

}
